package cn.edu.lingnan.service.impl;

import cn.edu.lingnan.common.JsonResult;
import cn.edu.lingnan.entity.User;
import cn.edu.lingnan.mapper.UserMapper;
import cn.edu.lingnan.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;
import org.springframework.util.DigestUtils;

import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.UUID;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 陈浩
 * @since 2022-06-24
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    // 注入持久层对象到业务层中使用
    @Autowired(required = false)
    private UserMapper userMapper;
    private final String salt = "SASADASDASDAWSDAS";

    //验证登录------------
    @Override
    public JsonResult<Void> dologin(String uAccount, String uPassWord, String uPower, HttpSession session) {

        //判断用户账号（手机号码）
        JsonResult<Void> result = checkLoginuAccount(uAccount);
        if(result.getCode() != 200){
            return result;
        }
        //密码不能为空
        if ("".equals(uPassWord) || uPassWord == null){
            System.out.println(uPassWord);
            return new JsonResult<>(501,"密码不能为空");
        }
        //根据账号（手机号）查询用户
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("u_account", uAccount);
        User user = userMapper.selectOne(queryWrapper);
        if(user == null){
            return new JsonResult<>(502, "账号不存在");
        }

        //获取密码和盐值
        String regMD5Pwd = user.getUPassWord();
        System.out.println("== === 获取账号的加密密码:"+regMD5Pwd);
        String md5Password = md5Password(uPassWord, salt);
        System.out.println("用户登录写的密码,获取加密后的数据:"+md5Password);
        if(regMD5Pwd.equals(md5Password) == false){
            return new JsonResult<>(503, "密码错误");
        }

        // 用户登录成功就绑定用户数据
        session.setAttribute("user", user);
        return new JsonResult<>(200,"√");

    }


    // 对用户登录的账号（手机号码）进行验证
    @Override
    public JsonResult<Void> checkLoginuAccount(String uAccount) {

        //判断手机号是否为空
        if ("".equals(uAccount) || uAccount == null){
            return new JsonResult<>(201,"账号（手机号）不能为空");
        }
        String regxPhone = "^((13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$";
        if( !(uAccount.matches(regxPhone) || uAccount.equals("")) ){
            return new JsonResult<>(202, "手机号码格式填写不正确");
        }
        // 唯一性判断，还没注册就提示没注册
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("u_Account",uAccount);
        User user = userMapper.selectOne(queryWrapper);
        if(user == null){
            return new JsonResult<>(203, "账号未注册，请先注册");
        }
        return new JsonResult<>(200, "√");
    }

    //封装一个方法，用于密码的加密
    private String md5Password(String uPassWord, String salt){
        String md5Pwd = uPassWord + salt;
        //调用 API 加密
        md5Pwd = DigestUtils.md5DigestAsHex(md5Pwd.getBytes());
        System.out.println("加密后的密码：" + md5Pwd);
        return md5Pwd;
    }

    //注册
    @Override
    public JsonResult<Void> doReg(String uName, String uAccount, String uPassWord, String confirmPwd, String uPower, String uEmail, HttpSession session) {

        //对账号进行判断（手机号）
        JsonResult<Void> result1 = checkReguAccount(uAccount);
        if (result1.getCode()!=200){
            return result1;
        }
        //姓名不能为空
        if ("".equals(uName) || uName == null){
            return new JsonResult<>(201, "姓名不能为空");
        }
        //验证邮箱
        JsonResult<Void> result3 = checkEmail(uEmail);
        if (result3.getCode()!=200){
            return  result3;
        }
        //验证密码一致性
        JsonResult<Void> result2 = checkuPasswordAndConfirmPwd(uPassWord,confirmPwd);
        if (result2.getCode()!=200){
            return  result2;
        }
        //密码加密
        //String salt = UUID.randomUUID().toString();//写死盐了,不用随机
        String md5Password = md5Password(uPassWord, salt);
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String format = LocalDateTime.now().format(dateTimeFormatter);
        //封装数据
        User user = new User()
                .setUName(uName).setUAccount(uAccount).setUEmail(uEmail)
                .setUPassWord(md5Password).setUPower(uPower).setURegTime(format);
        System.out.println(uAccount+"  "+uName+"11111111111111111");
        int row = userMapper.insert(user);
        if(row != 1){
            return new JsonResult<>(207, "注册失败，请稍后重试");
        }
        return new JsonResult<>(200, "注册成功");
    }

    //验证账号
    @Override
    public JsonResult<Void> checkReguAccount(String uAccount) {
        // 对参数判断
        if("".equals(uAccount) || uAccount == null){
            return new JsonResult<>(201, "账号不能为空");
        }
        // 判断账号的格式是否正确
        String regxPhone = "^((13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$";
        if( !(uAccount.matches(regxPhone) || uAccount.equals("")) ){
            return new JsonResult<>(202, "手机号码格式填写不正确");
        }
        //唯一性判断，注册过就不用注册了
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("u_Account", uAccount);
        User user = userMapper.selectOne(queryWrapper);
        if(user != null){
            return new JsonResult<>(203, "该账号已被注册");
        }
        return new JsonResult<>(200, "账号验证通过");
    }

    //验证密码的一致性
    @Override
    public JsonResult<Void> checkuPasswordAndConfirmPwd(String uPassWord, String confirmPwd) {
        //非空判断
        if("".equals(uPassWord) || uPassWord == null){
            return new JsonResult<>(201, "密码不能为空");
        }
        if("".equals(confirmPwd) || confirmPwd == null){
            return new JsonResult<>(202, "确认密码不能为空");
        }
        if(!uPassWord.equals(confirmPwd)){
            return new JsonResult<>(203, "两次密码不一致");
        }
        return new JsonResult<>(200, "OK");
    }

    //验证邮箱
    @Override
    public JsonResult<Void> checkEmail(String uEmail) {
        // 对参数判断
        if ("".equals(uEmail) || uEmail == null) {
            return new JsonResult<>(201, "邮箱不能为空");
        }
        // 判断邮箱的格式是否正确 qq 邮箱
        String regx = "[1-9]\\d{7,10}@qq\\.com";
        if (!uEmail.matches(regx)) {
            return new JsonResult<>(202, "邮箱格式错误");
        }
        return new JsonResult<>(200, "邮箱验证通过");
    }

}
